package com.example;

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.example.config.CustomUrlBlockHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {
    public static void main(String[] args) {
        init();
        SpringApplication.run(NacosConsumerApplication.class, args);
        initRtRule();
    }

    private static void init() {
        WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
    }

    private static void initRtRule() {
        List rules = new ArrayList();
        DegradeRule rule = new DegradeRule();
        rule.setResource("GET:http://nacos-provider/hi");//资源名称
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//降级模式，根据平均响应时间降级
        rule.setCount(1000);//设置平均响应时间为1000ms
        rule.setTimeWindow(10);//设置降级持续时间为10s
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }


    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
